package com.demo.jar;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class JarExtractor {
    public static void extractNestedJars(String jarFilePath, String outputDir) throws IOException {
        File outputDirFile = new File(outputDir);
        if (!outputDirFile.exists()) {
            outputDirFile.mkdirs();
        }

        JarFile jarFile = new JarFile(jarFilePath);
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String entryName = entry.getName();

            if (entryName.endsWith(".jar") && entryName.contains("passenger")) {
                System.out.println("符合提取条件的entryName="+entryName);
                // 这是一个嵌套的JAR文件
                String nestedJarPath = outputDir + File.separator + entryName;
                extractNestedJars(nestedJarPath, outputDir); // 递归提取嵌套的JAR文件
            } else if (entryName.endsWith(".class")) {
                // 这是一个class文件，
                System.out.println("class微博华北");
                System.out.println(entryName);
                String classPath = outputDir + File.separator + entryName;
                //extractFile(jarFile, classPath);
            }
        }

        jarFile.close();
    }

    private static void extractFile(JarFile jarFile, String outputPath) throws IOException {
        InputStream inputStream = jarFile.getInputStream(jarFile.getJarEntry(outputPath));
        OutputStream outputStream = new FileOutputStream(outputPath);

        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        inputStream.close();
        outputStream.close();
    }

    public static void main(String[] args) throws IOException {
        extractNestedJars("D:\\data\\passenger-management-bootstrap-3.1.2-SNAPSHOT.jar","D:\\data\\testPassenger");
    }
}